package com.kuang.service.WeiXinUser;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kuang.common.exception.ResultCodeEnum;
import com.kuang.common.exception.ValidationException;
import com.kuang.entity.WeiXinUser;
import com.kuang.mapper.WeixinUserMapper;
import com.kuang.vo.WeixinDataVo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class WeXinUserServiceImpl extends ServiceImpl<WeixinUserMapper, WeiXinUser> implements WeiXinUserService {
 /*   @Autowired
    private WeixinUserMapper weixinUserMapper;    */


    public WeiXinUser saveWeiXinUser(WeixinDataVo weixinDataVo){
        if(weixinDataVo==null){
          throw new ValidationException(ResultCodeEnum.SERVER_ERROR);
        }
        if(StringUtils.isEmpty(weixinDataVo.getOpenid())){
            throw  new ValidationException(ResultCodeEnum.UNKNOWN_REASON);
        }
        WeiXinUser userByOpenid = this.getUserByOpenid(weixinDataVo.getOpenid());
        if(userByOpenid==null){
            WeiXinUser user = new WeiXinUser();
            user.setUsername(weixinDataVo.getNickName());
            user.setPassword("");
            user.setOpenid(weixinDataVo.getOpenid());
            user.setAvatarUrl(weixinDataVo.getAvatarUrl());
            user.setCity(weixinDataVo.getCity());
            user.setCountry(weixinDataVo.getCountry());
            user.setGender(weixinDataVo.getGender());
  //          user.setNickName(weixinDataVo.getNickName());
            user.setProvince(weixinDataVo.getProvince());
            user.setActive(1);
            // 保存入库,在这里保存成功，mybatis会自动回填用户id到user对象中
            this.saveOrUpdate(user);
            return user;
        }
        return userByOpenid;

        //boolean save = this.save();
        //    weixinUserMapper.saveWeiXinUser(null);
    }

    public WeiXinUser getUserByOpenid(String openid) {
        if (StringUtils.isEmpty(openid)) {
            throw new ValidationException(ResultCodeEnum.EMPTY_ERROR);
        }
        LambdaQueryWrapper<WeiXinUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WeiXinUser::getOpenid, openid);
        return this.getOne(lambdaQueryWrapper);
    }
}
